package com.xl.studentpass.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xl.studentpass.entity.ImageInfoEntity;
import com.xl.studentpass.mapper.ImageMapper;
import com.xl.studentpass.service.ImageUploadService;
import com.xl.studentpass.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: xl
 * @createTime: 2023/5/25 16:20:56
 * @program: student-pass
 * @e-mail: 2199396150@qq.com
 * @description: 上传图片地址
 */
@RestController
@RequestMapping("/img")
@Slf4j
@Api(tags = "上传图片")
public class ImageController {

    @Resource
    ImageUploadService imageUploadService;
    @Resource
    ImageMapper imageMapper;


    @PostMapping("/task/upload")
    @ApiOperation("任务发布时上传图片的接口")
    //@SaCheckLogin
    public R taskUpload(@RequestParam(value = "img") MultipartFile[] imgFiles,
                        HttpServletRequest request) {
        log.info(this.getClass().getSimpleName() + "==============任务发布时上传图片的接口");
        Boolean checkpoint = checkpoint(imgFiles);
        if (checkpoint) {
            return R.error("文件上传失败");
        }

        if (ObjectUtils.isEmpty(imgFiles) || imgFiles.length < 1) {
            return R.error("文件上传失败");
        }
        List<Integer> urlIds = imageUploadService.uploadImage("task", imgFiles, request);
        if (!ObjectUtils.isEmpty(urlIds) && urlIds.size() > 0) {
            return R.ok("文件上传成功").put("urlIds", urlIds);
        } else {
            return R.error("文件上传失败");
        }
    }

    @PostMapping("/order/upload")
    @ApiOperation("任务完成时上传图片的接口")
    //@SaCheckLogin
    public R orderCompleteUpload(@RequestParam(value = "img") MultipartFile[] imgFiles,
                                 HttpServletRequest request) {

        log.info(this.getClass().getSimpleName() + "==========================任务完成时上传图片的接口");

        if (checkpoint(imgFiles)) {
            return R.error("文件上传失败");
        }

        if (ObjectUtils.isEmpty(imgFiles) || imgFiles.length < 1) {
            return R.error("文件上传失败");
        }
        List<Integer> urlIds = imageUploadService.uploadImage("order", imgFiles, request);
        if (!ObjectUtils.isEmpty(urlIds) && urlIds.size() > 0) {
            return R.ok("文件上传成功").put("urlIds", urlIds);
        } else {
            return R.error("文件上传失败");
        }
    }


    @PostMapping("/community/upload")
    @ApiOperation("社区用户上传图像的接口")
    public R communityUpload(@RequestParam(value = "img") MultipartFile[] imgFiles, HttpServletRequest request) {

        log.info(this.getClass().getSimpleName() + "=======================社区用户上传图像的接口");

        Boolean checkpoint = checkpoint(imgFiles);
        if (checkpoint) {
            return R.error("文件上传失败");
        }

        if (ObjectUtils.isEmpty(imgFiles) || imgFiles.length < 1) {
            return R.error("文件上传失败");
        }

        List<Integer> urlIds = imageUploadService.uploadImage("community", imgFiles, request);

        if (!ObjectUtils.isEmpty(urlIds) && urlIds.size() > 0) {
            return R.ok("文件上传成功").put("urlIds", urlIds);
        } else {
            return R.error("文件上传失败");
        }
    }

    @PostMapping("/head/upload")
    @ApiOperation("上传头像")
    public R updateHeadPicture(@RequestParam(value = "img") MultipartFile image, HttpServletRequest request) {

        int userId = StpUtil.getLoginIdAsInt();

        log.info(this.getClass().getSimpleName() + "===============上传头像");

        if (ObjectUtils.isEmpty(image)) {
            return R.error("文件上传失败");
        }
        List<Integer> urlsId = imageUploadService.uploadImage("head", new MultipartFile[]{image}, request, userId);
        if (ObjectUtils.isEmpty(urlsId) || urlsId.size() <= 0) {
            return R.error("头像上传失败");
        }
        return R.ok().put("urlId", urlsId);
    }

    @PostMapping("/image/urls/get")
    @ApiOperation("根据图像ids获取数据")
    public R getImageUrls(@RequestParam("urlIds") Integer[] urlsIds) {

        log.info(this.getClass().getSimpleName() + "====================根据图像id获取数据");

        if (ObjectUtils.isEmpty(urlsIds)) {
            return R.error("图像加载失败");
        }
        List<ImageInfoEntity> imageInfos = imageMapper.selectBatchIds(Arrays.asList(urlsIds));
        if (ObjectUtils.isEmpty(imageInfos) || imageInfos.size() <= 0) {
            return R.error("图像加载失败");
        }
        ArrayList<String> urls = new ArrayList<>();
        imageInfos.forEach(x -> urls.add(x.getImageUrl()));
        return R.ok().put("imageUrls", urls);
    }

    @PostMapping("/image/urls/delete")
    @ApiOperation("根据图片的ids删除图片")
    public R deleteImageUrls(@RequestParam("urlIds") Integer[] urlsIds) {
        log.info(this.getClass().getSimpleName() + "======================根据图片的ids删除图片");
        if (ObjectUtils.isEmpty(urlsIds)) {
            return R.error("图像删除失败");
        }
        int i = imageMapper.deleteBatchIds(Arrays.asList(urlsIds));
        if (i <= 0) {
            return R.error("删除失败");
        }
        return R.ok("删除成功");
    }

    private Boolean checkpoint(MultipartFile[] imgFiles) {
        for (MultipartFile imgFile : imgFiles) {
            if (!imgFile.getOriginalFilename().endsWith(".jpeg") &&
                    !imgFile.getOriginalFilename().endsWith(".png") &&
                    !imgFile.getOriginalFilename().endsWith(".jpg")) {
                return true;
            }
        }
        return false;
    }
}
